#include "login.h"
#include "ui_login.h"

LoginWindow::LoginWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::LoginWindow)
{
	ui->setupUi(this);
	connect(ui->loginPushButton, &QPushButton::clicked, this, &LoginWindow::login);
	connect(ui->regPushButton, &QPushButton::clicked, this, &LoginWindow::registry);
	User::readDataFile();
}

LoginWindow::~LoginWindow()
{
	User::saveDataFile();
	delete ui;
}

void LoginWindow::logoutSlot()
{
	ui->nameLineEdit->clear();
	ui->passwdLineEdit->clear();
	this->show();
}

void LoginWindow::login()
{
	if (ui->nameLineEdit->text() == "" || ui->passwdLineEdit->text() == "")
	{
		QMessageBox::critical(this, WINDOW_TITLE, "信息不能为空！");
		return;
	}
	userTemp.setName(ui->nameLineEdit->text());
	userTemp.setPasswd(ui->passwdLineEdit->text());

	if (userTemp.login())
	{
		this->hide();
		emit loginSignal(userTemp);
	}
	else { QMessageBox::critical(this, WINDOW_TITLE, "用户名或密码错误！"); }
}

void LoginWindow::registry()
{
	if (ui->nameLineEdit->text() == "" || ui->passwdLineEdit->text() == "")
	{
		QMessageBox::critical(this, WINDOW_TITLE, "信息不能为空！");
		return;
	}
	userTemp.setName(ui->nameLineEdit->text());
	userTemp.setPasswd(ui->passwdLineEdit->text());

	if (userTemp.registry())
	{
		QMessageBox::information(this, WINDOW_TITLE, "新用户注册成功！");
		this->hide();
		emit loginSignal(userTemp);
	}
	else { QMessageBox::critical(this, WINDOW_TITLE, "该用户名已被注册！"); }
}
